package at.chl.genetic.function.math;

import at.chl.genetic.function.IGeneticFunction;
import at.chl.genetic.function.math.factory.MathFunctionFactory;
import at.chl.genetic.function.math.ifstatement.IIfStatement;
import at.chl.genetic.function.math.node.AbstractMathDecisionNode;
import at.chl.genetic.function.math.node.FunctionNode;
import at.chl.genetic.function.math.request.IIfStatementRequest;
import at.chl.genetic.function.math.request.MathFunctionRequest;
import at.chl.genetic.function.math.result.MathFunctionResult;
import at.chl.genetic.function.math.types.IfStatementType;

public class IfFunction extends AbstractMathFunction{
	
	private static final String NAME = "IF";
	private static final int DEFAULT_CHILDCOUNT = 4;
	private FunctionNode parentNode;
	private int childCount;
	private IIfStatement ifStatement;
	
	public IfFunction(IIfStatement ifStatement) {
		super(NAME);
		this.ifStatement=ifStatement;
		this.childCount=DEFAULT_CHILDCOUNT;
	}
	
	@Override
	public MathFunctionResult doFunction(MathFunctionRequest request) {
		
		//EXC nullpointer parent
		
		
		
		AbstractMathDecisionNode node1=(AbstractMathDecisionNode)parentNode.getChildNodes().get(0);
		AbstractMathDecisionNode node2=(AbstractMathDecisionNode)parentNode.getChildNodes().get(1);
		AbstractMathDecisionNode node3=(AbstractMathDecisionNode)parentNode.getChildNodes().get(2);
		AbstractMathDecisionNode node4=(AbstractMathDecisionNode)parentNode.getChildNodes().get(3);
		
		long res1=node1.evaluate(request).getResult();
		long res2=node2.evaluate(request).getResult();
		
		boolean decision=false;
		
		IIfStatementRequest statementRequest=MathFunctionFactory.createIfStatementRequest(res1,res2,request);
		
		//rock the statement
		decision=ifStatement.calculate(statementRequest);
		
		if(decision){
			return node3.evaluate(request);
		}else{
			return node4.evaluate(request);
		}
		
		
	}

	@Override
	public String getName() {
		return super.getName()+" "+ifStatement.getStatementName();
	}

	@Override
	public int getChildCount() {
		return childCount;
	}
	public void setParentNode(FunctionNode parentNode) {
		this.parentNode = parentNode;
	}

	@Override
	public IGeneticFunction cloneFunction() {
		IGeneticFunction clone=new IfFunction(ifStatement);
		return clone;
	}
	

}
